<template>
  <el-form
      ref="ruleFormRef"
      :model="state.userForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
      size="large"
  >
    <el-row>
      <el-col :span="12">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="state.userForm.username" class="input-width" disabled/>
          </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="state.userForm.nickname" class="input-width"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="state.userForm.phone" class="input-width"/>
        </el-form-item>
        <el-form-item label="个性签名" prop="signature">
          <el-input v-model="state.userForm.signature" class="input-width"/>
        </el-form-item>
      </el-col>
      <el-col :span="12"><div class="grid-content ep-bg-purple-light" />
        <el-form-item label="头像地址" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :show-file-list="false"
              :http-request="handleAvatarHttp"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="state.userForm.avatar" :src="state.userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="state.userForm.email" style="width: 500px"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="state.userForm.qq" class="input-width" style="width: 500px"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="Gitee地址" prop="gitee">
          <el-input v-model="state.userForm.gitee" class="input-width" style="width: 500px"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="GitHub地址" prop="github">
          <el-input v-model="state.userForm.github" class="input-width" style="width: 500px"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确认修改
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { Plus} from '@element-plus/icons-vue'
import {onMounted, ref} from "vue";
import { reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import {ElMessage, ElNotification} from "element-plus";
import request from "../../utils/request.js";
import {getUserInfoByToken,edit} from "../../api/user.js";
import router from "../../router";

// 初始化
const ruleFormRef = ref<FormInstance>()
const state = reactive({
  userForm: {
    id: null,
    username: "",
    nickname: "",
    phone: "",
    email: "",
    qq: "",
    signature: "",
    avatar: "",
    gitee: "",
    github: "",
  }
})

// 规则校验
const rules = reactive<FormRules>({
  nickname: [
    {required: true, message: '昵称不能为空', trigger: 'blur'},
    { min: 3, max: 20, message: '昵称长度必须在 5 到 20位之间', trigger: 'blur' },
  ],
  phone: [
    {required: true, message: '手机号码不能为空', trigger: 'blur'},
    { min: 11, max: 11, message: '格式不正确', trigger: 'blur' },
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    { min: 10, max: 25, message: '昵称长度必须在  10 to 25', trigger: 'blur' },
  ],
  qq: [
    {required: true, message: 'QQ不能为空', trigger: 'blur'},
  ],
  signature: [
    {required: true, message: '个性签名不能为空', trigger: 'blur'},
    { min: 1, max: 50, message: '个性签名必须在 1 到 50之间', trigger: 'blur' },
  ],
  avatar: [
    {required: true, message: '头像不能为空', trigger: 'blur'},
  ],
  gitee: [
    {required: true, message: 'gitee开源地址不能为空', trigger: 'blur'},
    { min: 10, max: 100, message: 'gitee开源地址必须在 10 到 100之间', trigger: 'blur' },
  ],
  github: [
    {required: true, message: 'github开源地址不能为空', trigger: 'blur'},
    { min: 10, max: 100, message: 'github开源地址必须在 10 到 100之间', trigger: 'blur' },
  ],
})

// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      edit(state.userForm).then((res:any) => {
        if(res.code == '200' || res.code == 200){
          ElNotification({
            title: 'success',
            message: res.msg,
            type: 'success',
          })
        }else {
          ElNotification({
            title: 'error',
            message: res.msg,
            type: 'error',
          })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 上传头像
const handleAvatarHttp: UploadProps['onSuccess'] = (uploadFile: any, uploadFiles: any) => {
  // 配置
  let param = new FormData();
  param.append("image",uploadFile.file);
  let config = {headers: {"Content-Type": "multipart/form-data"}}
  let url = "/upload";

  // 发送请求
  request.post(url,param,config).then((res: any)=>{
    state.userForm.avatar = res.data
  })
}

// 上传头像的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不超过2MB!')
    return false
  }
  return true
}

// 获取用户信息
onMounted(()=>{
  let token = sessionStorage.getItem("TOKEN");
  if (typeof(token) == "undefined") {
    ElNotification({
      title: 'error',
      message: "用户信息已过期！",
      type: 'error',
    })
    router.push("/")
    return;
  }
  getUserInfoByToken().then((res:any) => {
    if(res.code == '200' || res.code == 200){
      state.userForm = res.data;
    }else {
      ElNotification({
        title: 'error',
        message: res.msg,
        type: 'error',
      })
    }
  })
})
const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>

<style scoped>

.input-width{
  width: 300px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
